import java.util.HashMap;
import java.util.Set;

/**
 * class Maze
 *   - contains the whole infomation of the game
 */
public class Maze {
	private int n; // the maze's size
	private int m; // the treasures' number
	
	private int [][] treasure; // how many treasures are at the point (i, j)
	private HashMap<String, Integer> treasureList; // be convenient to send message to client.
	
	private HashMap<String, Player> playerList; // <id, Player>
	
	public Maze(int n, int m){
		this.n = n;
		this.m = m;
		treasure = new int [n][n];
		playerList = new HashMap<String, Player>();
		treasureList = new HashMap<String, Integer>();
		for (int i=0; i<n; i++){
			for (int j=0; j<n; j++){
				treasure[i][j] = 0;
			}
		}
	}
	
	public void buildTreasure() {
		String s = "";
		int x=0, y=0;
		// in order to be more average
		for (int k=0; k<m; k++){
			x = (int)(Math.random()*n);
			y = (int)(Math.random()*n);
			treasure[x][y] ++;
			s = Integer.valueOf(x).toString() + ' ' + Integer.valueOf(y).toString();
			treasureList.put(s, treasure[x][y]);
		}
	}
	
	public int getN() {
		return n;
	}

	public void setN(int n) {
		this.n = n;
	}

	public int getM() {
		return m;
	}

	public void setM(int m) {
		this.m = m;
	}
	
	public Player getPlayer(String id) {
		return playerList.get(id);
	}

	public void addPlayer(String id, Player p) {
		playerList.put(id, p);
	}
	
	public Set<String> getPlayerIdSet() {
		return playerList.keySet();
	}

	public int getTreasure(int x, int y) {
		return treasure[x][y];
	}
	
	public void setTreasure(int x, int y, int num) {
		treasure[x][y] = num;
		String s = Integer.valueOf(x).toString() + ' ' + Integer.valueOf(y).toString();
		treasureList.put(s, num);
	}
	
	// for send treasure list message
	public String getTreasureList() {
		String res = "";
		for (String s : treasureList.keySet()) {
			res = res + " " + s + " " + treasureList.get(s); // x y num
		}
		return res;
	}

	// only one player can look and get one treasure at the same time
	// 1. this method return the original treasure number of (x,y)
	// 2. and change this number to 0 (if it > 0)
	public int clearTreasure(int x, int y) {
		int treasureXY = treasure[x][y];
		
		if (treasureXY > 0) {
			m = m - treasure[x][y];
			treasureList.remove(Integer.valueOf(x).toString()+' '+Integer.valueOf(y).toString());
			treasure[x][y] = 0;
		}
		
		return treasureXY;
	}
}
